package com.gsmvn.ngamgaixinh;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.appota.congaixinh.model.Banner;
import com.appota.congaixinh.model.Image;
import com.appota.congaixinh.model.Photo;
import com.appota.vn.network.HttpHelper;
import com.appota.vn.util.CommonUtils;
import com.facebook.FacebookException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Request.GraphUserCallback;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

public class FavoriteActivity extends Activity {
	int offset = 0;
	boolean isCompleteLoop = false;
	HackyViewPager viewPager;
	ArrayList<Photo> photos = new ArrayList<Photo>();
	LinearLayout ll_loading;
	boolean useFullscreen = false;
	boolean isShowNavButton = true;
	LinearLayout llNoPhoto;

	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	private DataSource datasource;
	private ArrayList<String> list;
	protected GraphUser graphUser;
	protected Menu menu;

	private void getUserIfvailable() {
		Request requestme = Request.newMeRequest(Session.getActiveSession(),
				new GraphUserCallback() {

					@Override
					public void onCompleted(GraphUser user, Response response) {
						// TODO Auto-generated method stub
						if (user != null) {
							graphUser = user;
							onPrepareOptionsMenu(menu);
						}
					}
				});
		RequestAsyncTask asyncTask = new RequestAsyncTask(requestme);
		asyncTask.execute();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		if (isFBActive()) {
			if (graphUser != null && menu != null)
				menu.getItem(0).getSubMenu().getItem(0)
						.setTitle(getResources().getString(R.string.hello) + graphUser.getUsername());

		} else {
			menu.getItem(0).getSubMenu().getItem(0).setEnabled(true);
		}
		try {
			if (getSharedPreferences("kenh18cong", 0).getBoolean(
					"notification", true)) {
				menu.getItem(0).getSubMenu().getItem(2)
				.setTitle(getResources().getString(R.string.baoanhmoi)+"("+getResources().getString(R.string.show_notifi)+")");
			} else {
				menu.getItem(0).getSubMenu().getItem(2)
				.setTitle(getResources().getString(R.string.baoanhmoi)+"("+getResources().getString(R.string.show_notifi)+")");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return true;
	}

	private StatusCallback callback = new StatusCallback() {

		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			// TODO Auto-generated method stub
			if (state == SessionState.OPENED) {
				// dialog.dismiss();
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				if (graphUser == null)
					getUserIfvailable();
			}
		}
	};

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.login:
			if (graphUser == null) {
				Session session = Session.getActiveSession().openActiveSession(
						this, true, callback);

			}
			return true;
		case R.id.favorite:
			onBackPressed();
			return true;
			
		case R.id.notification:
			String msg = "";
			if (getSharedPreferences("kenh18cong", 0).getBoolean(
					"notification", true)) {
				msg = getResources().getString(R.string.tatbaoanhmoi);
			} else {
				msg = getResources().getString(R.string.batbaoanhmoi);
			}

			AlertDialog.Builder builder1 = new Builder(FavoriteActivity.this);
			builder1.setTitle(getResources().getString(R.string.cauhinh))
					.setMessage(msg)
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									if (getSharedPreferences("kenh18cong", 0)
											.getBoolean("notification", true)) {
										getSharedPreferences("congaixinh", 0)
												.edit()
												.putBoolean("notification",
														false).commit();
									} else {
										getSharedPreferences("kenh18cong", 0)
												.edit()
												.putBoolean("notification",
														true).commit();
									}
									onPrepareOptionsMenu(menu);
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
			AlertDialog dialog1 = builder1.create();
			dialog1.show();
			return true;

		case R.id.dowload:
			Intent intent1 = new Intent();
			intent1.setAction(Intent.ACTION_VIEW);
			intent1.addCategory(Intent.CATEGORY_BROWSABLE);
			intent1.setData(Uri.parse(MainActivity.GOOGLE_LINK));
			startActivity(intent1);
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onStart() {
		super.onStart();
		tracker.sendView("GaiXinhFavorite");
	}

	private static final String TRACKER_ID = "UA-37513871-5";
	private Tracker tracker;
	private AlertDialog dialog;
	public Banner banner;
	private ImageView imgBanner;
	private TextView txtBacktoMain;
	private RelativeLayout llBanner;
	private ImageButton btnCloseBanner;

	private void initPhoto(Response response) {
		Log.e("", "res photo single " + response.toString());
		Gson gson = new Gson();
		try {
			GraphObject graphObject = response.getGraphObject();
			if (graphObject != null) {
				JSONObject grap = graphObject.getInnerJSONObject();
				JSONArray array = grap.getJSONArray("data");
				if (array.length() > 0) {
					int object_count = array.getJSONObject(0)
							.getJSONArray("fql_result_set").length();
					for (int i = 0; i < object_count; i++) {
						Photo photo = new Photo();
						photos.add(photo);
					}
					for (int i = 0; i < array.length(); i++) {
						JSONObject object = array.getJSONObject(i);
						String nameobject = object.getString("name");
						JSONArray fqlresult = object
								.getJSONArray("fql_result_set");
						if (nameobject.equals("photos")) {
							int object_count1 = fqlresult.length();
							for (int j = 0; j < object_count1; j++) {
								JSONObject object1 = fqlresult.getJSONObject(j);
								ArrayList<Image> images = new ArrayList<Image>();
								JSONArray imgArray = object1
										.getJSONArray("images");
								for (int k = 0; k < imgArray.length(); k++) {
									JSONObject object2 = imgArray
											.getJSONObject(k);
									Image image = gson.fromJson(
											object2.toString(), Image.class);
									// Log.d("image", "image Link " +
									// image.getSource());
									images.add(image);
								}
								String caption = object1.getString("caption");
//								for (String string : CommonStatic.avoid_strings) {
//									if (caption.contains(string)) {
//										Log.e("", "apear need dellete string "
//												+ string + "  delete them ");
//										caption = caption.replace(string, "");
//									}
//								}
								String photo_id = object1
										.getString("object_id");
								Log.e("", "photo_id " + photo_id);
								if (datasource.isAvailable(String
										.valueOf(photo_id)))
									photos.get(j + offset).isFavorite = true;
								String link = object1.getString("link");
								photos.get(j + offset).setLink(link);
								photos.get(j + offset).setId(
										String.valueOf(photo_id));
								photos.get(j + offset).setName(caption);
								photos.get(j + offset).setImages(images);
								String album_id = object1
										.getString("album_object_id");
								photos.get(j + offset).setAlbum_object_id(
										album_id);

							}
						} else if (nameobject.equals("commentlikeinfo")) {
							for (int j = 0; j < fqlresult.length(); j++) {
								JSONObject object1 = fqlresult.getJSONObject(j);
								JSONObject like_info = object1
										.getJSONObject("like_info");
								boolean user_like = like_info
										.getBoolean("user_likes");
								photos.get(j + offset).setIs_user_like(
										user_like);
								int like_count = like_info.getInt("like_count");
								JSONObject comment_info = object1
										.getJSONObject("comment_info");
								int comment_count = comment_info
										.getInt("comment_count");
								photos.get(j + offset)
										.setLike_count(like_count);
								photos.get(j + offset).setComment_count(
										comment_count);
							}

						}
					}

					if (offset == list.size() - 1)
						isCompleteLoop = true;
				}

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (isCompleteLoop) {
			if (viewPager.getAdapter() == null) {
				PagerAdapter adapter = new PagerAdapter(photos,
						FavoriteActivity.this);
				viewPager.setAdapter(adapter);
			} else {
				viewPager.getAdapter().notifyDataSetChanged();
			}
			viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
			if (ll_loading.getVisibility() == View.VISIBLE) {
				Animation animation_left_right = AnimationUtils.loadAnimation(
						FavoriteActivity.this, R.anim.slide_right_to_left);
				ll_loading.startAnimation(animation_left_right);
				ll_loading.setVisibility(View.GONE);
			}
		} else {
			offset += 1;
			getAPhoto();
		}

	}

	@Override
	public void onResume() {
		super.onResume();
		if (graphUser == null) {
			getUserIfvailable();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (datasource.isOpen()) {
			datasource.close();
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		llNoPhoto = (LinearLayout) findViewById(R.id.noFavorite);
		txtBacktoMain = (TextView) findViewById(R.id.txtBacktoMain);
		txtBacktoMain.setText(Html
				.fromHtml("<a hfref='' >"+getResources().getString(R.string.nofavorite)+"</a>"));
		txtBacktoMain.setMovementMethod(LinkMovementMethod.getInstance());

		txtBacktoMain.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});
		tracker = GoogleAnalytics.getInstance(this).getTracker(TRACKER_ID);
		initImageLoader();
		datasource = new DataSource(this);
		datasource.open();
		viewPager = (HackyViewPager) findViewById(R.id.view_pager);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
			}

			boolean b = false;

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				Log.e("", "arg0" + arg0 + "arg1" + arg1 + "arg2" + arg2);
				if (arg0 == photos.size() - 1 && !b) {
					Toast.makeText(FavoriteActivity.this,
							getResources().getString(R.string.hetanhyeuthich), 2000).show();
					b = true;
					Handler handler = new Handler();
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							b = false;
						}
					}, 2000);
				}
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				Log.e("", "onPageScrollStateChanged " + arg0);
			}
		});
		ll_loading = (LinearLayout) findViewById(R.id.imgloading);
		imgBanner = (ImageView) findViewById(R.id.imgBanner);
		imgBanner.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent1 = new Intent();
				intent1.setAction(Intent.ACTION_VIEW);
				intent1.addCategory(Intent.CATEGORY_BROWSABLE);
				Log.e("", "url banner " + banner.url);
				intent1.setData(Uri.parse(banner.url));
				startActivity(intent1);

			}
		});

		llBanner = (RelativeLayout) findViewById(R.id.rlBanner);
		btnCloseBanner = (ImageButton) findViewById(R.id.closeBanner);
		btnCloseBanner.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				llBanner.setVisibility(View.GONE);
				handler.postDelayed(showBannerRunnable, time_to_show_banner);
			}
		});
		getAPhoto();
		new GetAccessTokenAsync().execute();
	}

	public void showMessageDialog(int title, int msg) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(getResources().getString(title))
				.setMessage(getResources().getString(msg))
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	private void getAPhoto() {
		// TODO Auto-generated method stub
		list = datasource.getList();

		if (list.size() != 0) {
			if (CommonUtils.checkNetworkAvaliable(this)) {
				String fqlQuery = "{"
						+ "'photos':'select caption,images,created,object_id,link,album_object_id from photo where object_id="
						+ list.get(offset)
						+ " limit 25  "

						+ "',"
						+ "'commentlikeinfo':'select like_info, comment_info from photo where object_id="
						+ list.get(offset) + " limit 25 " + "'," + "}";
				Log.e("", fqlQuery);
				Bundle params = new Bundle();
				params.putString("q", fqlQuery);
				Request request = new Request(null, "/fql", params,
						HttpMethod.GET, new Request.Callback() {

							@Override
							public void onCompleted(Response response) {
								// TODO Auto-generated method stub
								initPhoto(response);
							}
						});
				RequestAsyncTask asyncTask = new RequestAsyncTask(request);
				asyncTask.execute();
			} else
				showMessageDialog(R.string.error_connection,
						R.string.error_connection_msg);

		} else {
			llNoPhoto.setVisibility(View.VISIBLE);
			if (ll_loading.getVisibility() == View.VISIBLE) {
				Animation animation_left_right = AnimationUtils.loadAnimation(
						FavoriteActivity.this, R.anim.slide_right_to_left);
				ll_loading.startAnimation(animation_left_right);
				ll_loading.setVisibility(View.GONE);
			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		menu.getItem(0).getSubMenu().getItem(1)
				.setTitle(R.string.menu_favorite_backto_main);
		menu.getItem(0).getSubMenu().getItem(1).setIcon(R.drawable.home);
		menu.getItem(0).getSubMenu().getItem(1).setIcon(null);
		this.menu = menu;
		return true;
	}

	public class PagerAdapter extends android.support.v4.view.PagerAdapter {
		ArrayList<Photo> photos;
		private Context context;

		public PagerAdapter(ArrayList<Photo> photos, Context context) {
			super();
			this.photos = photos;
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return photos.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return (arg0 == ((View) arg1));
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			// TODO Auto-generated method stub
			Log.e("", "instantiateItem position " + position);
			View view = LayoutInflater.from(context).inflate(
					R.layout.item_viewpager, null);
			PhotoView img = (PhotoView) view.findViewById(R.id.img);
			TextView txtLike = (TextView) view.findViewById(R.id.txtLike);
			TextView txtComment = (TextView) view.findViewById(R.id.txtComment);
			final LinearLayout llLoadPhoto = (LinearLayout) view
					.findViewById(R.id.llloading);
			final TextView txtloadphoto = (TextView) view
					.findViewById(R.id.txtloadphoto);
			imageLoader.displayImage(photos.get(position).getImages().get(0)
					.getSource(), img, options, new ImageLoadingListener() {

				@Override
				public void onLoadingStarted() {
					// TODO Auto-generated method stub
					llLoadPhoto.setVisibility(View.VISIBLE);
					txtloadphoto.setText(getResources().getString(R.string.dangloadanh));
				}

				@Override
				public void onLoadingFailed(FailReason arg0) {
					// TODO Auto-generated method stub
					llLoadPhoto.setVisibility(View.VISIBLE);
				}

				@Override
				public void onLoadingComplete(Bitmap arg0) {
					// TODO Auto-generated method stub
					llLoadPhoto.setVisibility(View.GONE);
				}

				@Override
				public void onLoadingCancelled() {
					// TODO Auto-generated method stub

				}
			});
			imageLoader.displayImage(photos.get(position).getImages().get(0)
					.getSource(), img, options);
			txtLike.setText(this.photos.get(position).getLike_count() + "");
			txtComment.setText(this.photos.get(position).getComment_count()
					+ "");
			LinearLayout imgLke = (LinearLayout) view
					.findViewById(R.id.imageLike);
			imgLke.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

				}
			});
			LinearLayout imgComment = (LinearLayout) view
					.findViewById(R.id.imageComment);
			imgComment.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(FavoriteActivity.this,
							CommentActivity.class);
					Log.e("", "photo_id " + photos.get(position).getId());
					intent.putExtra("photo_id", photos.get(position).getId());
					intent.putExtra("like_count", photos.get(position)
							.getLike_count());
					intent.putExtra("is_user_like", photos.get(position)
							.isIs_user_like());
					intent.putExtra("album_id", photos.get(position)
							.getAlbum_object_id());
					startActivity(intent);
				}
			});
			LinearLayout btnWallpaper = (LinearLayout) view
					.findViewById(R.id.wallpaper);

			final LinearLayout llFavorite = (LinearLayout) view
					.findViewById(R.id.llfavorite);

			final ImageView btnFavorite = (ImageView) view
					.findViewById(R.id.favorite);

			btnWallpaper.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog.Builder builder = new Builder(
							FavoriteActivity.this);
					builder.setTitle("ThÃ´ng bÃ¡o")
							.setMessage(
getResources().getString(R.string.setwallpaper))
							.setPositiveButton("Ok",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											new SetWallPaperAsync()
													.execute(new Integer[] { position });
											dialog.dismiss();
										}
									})
							.setNegativeButton("Cancel",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();
										}
									});
					AlertDialog dialog = builder.create();
					dialog.show();
				}
			});
			btnFavorite.setImageResource(R.drawable.deleteicon);
			btnFavorite.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					datasource.open();
					datasource.delete(photos.get(position).getId());
					Log.e("", "photos.size() " + photos.size());

					FavoriteActivity.this.photos.remove(position);
					PagerAdapter adapter = new PagerAdapter(
							FavoriteActivity.this.photos, FavoriteActivity.this);
					viewPager.setAdapter(adapter);
					if (photos.size() == 0) {
						llNoPhoto.setVisibility(View.VISIBLE);
					}

				}
			});
			final ImageView btnNext = (ImageView) view
					.findViewById(R.id.btnNext);
			final ImageView btnPrevious = (ImageView) view
					.findViewById(R.id.btnPrevious);
			if (!isShowNavButton) {
				btnNext.setVisibility(View.GONE);
				btnPrevious.setVisibility(View.GONE);
			}
			btnNext.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (position == photos.size() - 1) {
					} else {
						viewPager.setCurrentItem(
								viewPager.getCurrentItem() + 1, true);
					}

				}
			});

			btnPrevious.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (position != 0) {
						viewPager.setCurrentItem(
								viewPager.getCurrentItem() - 1, true);
					}

				}
			});
			img.setOnPhotoTapListener(new OnPhotoTapListener() {
				@TargetApi(Build.VERSION_CODES.HONEYCOMB)
				@SuppressLint("NewApi")
				@Override
				public void onPhotoTap(View view, float x, float y) {
					// TODO Auto-generated method stub
					if (!useFullscreen) {
						getActionBar().hide();
						btnNext.setVisibility(View.GONE);
						btnPrevious.setVisibility(View.GONE);
						isShowNavButton = false;
						for (int i = 0; i < viewPager.getChildCount(); i++) {
							View view1 = viewPager.getChildAt(i);
							view1.findViewById(R.id.btnNext).setVisibility(
									View.GONE);
							view1.findViewById(R.id.btnPrevious).setVisibility(
									View.GONE);
						}
						getWindow().addFlags(
								WindowManager.LayoutParams.FLAG_FULLSCREEN);
						getWindow()
								.clearFlags(
										WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
						Toast.makeText(FavoriteActivity.this,
								getResources().getString(R.string.zoomanh),
								Toast.LENGTH_LONG).show();
						useFullscreen = true;
					} else {
						getActionBar().show();
						for (int i = 0; i < viewPager.getChildCount(); i++) {
							View view1 = viewPager.getChildAt(i);
							view1.findViewById(R.id.btnNext).setVisibility(
									View.VISIBLE);
							view1.findViewById(R.id.btnPrevious).setVisibility(
									View.VISIBLE);
						}
						isShowNavButton = true;
						btnNext.setVisibility(View.VISIBLE);
						btnPrevious.setVisibility(View.VISIBLE);
						isShowNavButton = true;
						getWindow()
								.addFlags(
										WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
						getWindow().clearFlags(
								WindowManager.LayoutParams.FLAG_FULLSCREEN);
						useFullscreen = false;
					}
				}
			});

			RelativeLayout imgShareFaceBook = (RelativeLayout) view
					.findViewById(R.id.shareFB);
			final ProgressBar fbProgressBar = (ProgressBar) view
					.findViewById(R.id.progressFB);
			imgShareFaceBook.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!isFBActive()) {
						showLoginFaceBookDialog();
						// make request to the /me API
					} else {
						fbProgressBar.setVisibility(View.VISIBLE);
						Session session = Session.getActiveSession();
						if (session != null) {
							JSONObject param = new JSONObject();
							try {
								if (CommonUtils
										.checkNetworkAvaliable(FavoriteActivity.this)) {
									param.put("message", photos.get(position)
											.getName());
									param.put("link", photos.get(position)
											.getLink());
									Request request = Request.newPostRequest(
											session, "/me/feed",
											GraphObject.Factory.create(param),
											new Request.Callback() {
												@Override
												public void onCompleted(
														Response response) {
													Log.e("",
															"res share fb "
																	+ response
																			.toString());
													if (response.getError() == null) {
														fbProgressBar
																.setVisibility(View.GONE);
														Toast.makeText(
																FavoriteActivity.this,
																getResources().getString(R.string.share_facebook),
																Toast.LENGTH_SHORT)
																.show();
													}
												}
											});
									request.executeAsync();
								} else
									showMessageDialog(
											R.string.error_connection,
											R.string.error_connection_msg);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					}
				}
			});

			view.setTag(this.photos.get(position));
			container.addView(view);

			return view;
		}

	}

	public boolean isFBActive() {
		Session session = Session.getActiveSession();
		if (session == null) {
			return false;
		}
		return session.isOpened();
	}

	private void showLoginFaceBookDialog() {
		View view1 = LayoutInflater.from(FavoriteActivity.this).inflate(
				R.layout.dialog, null);
		LoginButton ok = (LoginButton) view1.findViewById(R.id.authButton);
		ok.setOnErrorListener(new OnErrorListener() {

			@Override
			public void onError(FacebookException error) {
				// TODO Auto-generated method stub
				Toast.makeText(FavoriteActivity.this, error.toString(), 2000)
						.show();
				Log.e("", error.toString());
			}
		});
		ArrayList<String> per = new ArrayList<String>();
		ArrayList<String> per1 = new ArrayList<String>();
		per.add("user_photos");
		per.add("publish_stream");

		ok.setPublishPermissions(per);
		AlertDialog.Builder buider = new Builder(FavoriteActivity.this);
		buider.setTitle(getResources().getString(R.string.pop_up_title))
				.setView(view1);
		dialog = buider.create();
		dialog.show();

	}

	public class SetWallPaperAsync extends AsyncTask<Integer, Void, Void> {
		@Override
		protected Void doInBackground(Integer... arg0) {
			// TODO Auto-generated method stub
			int position = arg0[0];
			WallpaperManager myWallpaperManager = WallpaperManager
					.getInstance(getApplicationContext());
			try {
				Log.e("", photos.get(position).getImages().get(0).getSource());
				InputStream in = new URL(photos.get(position).getImages()
						.get(0).getSource()).openStream();
				myWallpaperManager.setStream(in);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			Toast.makeText(FavoriteActivity.this, "Set WallPaper thành công",
					Toast.LENGTH_SHORT).show();
		}
	}

	private void initImageLoader() {
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.ic_launcher).cacheInMemory()
				.cacheOnDisc().build();
	}

	public class GetBannerAsync extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String rs = HttpHelper.requestBanner(accestoken);
			return rs;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if (!result.equals("")) {
				if (JsonUtil.getStatus(result)) {
					banner = JsonUtil.getBanner(result);
					if (banner != null) {
						llBanner.setVisibility(View.VISIBLE);
						DisplayImageOptions options1 = new DisplayImageOptions.Builder()
								.imageScaleType(
										ImageScaleType.EXACTLY_STRETCHED)
								.build();
						imageLoader.displayImage(banner.images, imgBanner,
								options1);
					}
				}
			} else
				showMessageDialog(R.string.error_connection,
						R.string.error_connection_msg);

		}
	}

	Handler handler = new Handler();

	Runnable showBannerRunnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			llBanner.setVisibility(View.VISIBLE);
		}
	};

	int time_to_show_banner = 60 * 1000;
	public String accestoken;

	public class GetAccessTokenAsync extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			return HttpHelper.getAccesToken();
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if (!result.equals("")) {
				if (JsonUtil.getStatus(result)) {
					accestoken = JsonUtil.getAccessToken(result);
					new GetBannerAsync().execute();
				}
			}
		}
	}

}
